<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/12
 * Time: 19:33

 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com

 */


namespace app\admin\controller;

use app\common\model\AmountLog;
use app\common\model\MessageTemplate;
use app\Request;

class Dazi
{
    /**
     * 搭子列表

     */
    public function daziList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where =[] ;
        $where[] = ['d.status','<>',6];
        if ( isset($param['status']) && !empty($param['status']) ){
            $where[] = ['d.status','=',$param['status']];
        }
        if (isset($param['son_tab']) && !empty($param['son_tab'])){
            $where[] = ['d.son_tab','=',$param['son_tab']];
        }
        if (isset($param['nickname']) && !empty($param['nickname'])){
            $where[] = ['u.nickname','like','%'.$param['nickname'].'%'];
        }
        if (isset($param['phone']) && !empty($param['phone'])){
            $where[] = ['u.phone','=',$param['phone']];
        }
        if (isset($param['uid']) && !empty($param['uid'])){
            $where[] = ['d.uid','=',$param['uid']];
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['d.title','like','%'.$param['title'].'%'];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])){
            $where[] = ['d.create_time','>=',strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])){
            $where[] = ['d.create_time','<=',strtotime($param['end_time'])];
        }
        $daziModel = new \app\common\model\Dazi();
        $list = $daziModel
            ->alias('d')
            ->leftJoin('user u', 'd.uid = u.id')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->order('d.create_time','desc')
            ->where($where)
            ->field('d.*,u.nickname,u.avatar,t.name,t.type_css')
            ->limit($start,$limit)->select()->toArray();
        $count = $daziModel->alias('d')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->where($where)->count();
        if ($list){
            $daziId  = array_column($list,'id');
            $daziJoinModel = new \app\common\model\DaziJoin();
            $daziJoinData = $daziJoinModel->where('dazi_id','in',$daziId)->select()->toArray();
            if ($daziJoinData){
                $daziJoinUid  = array_column($daziJoinData,'uid');
                $userModel = new \app\common\model\User();
                $userData = $userModel->where('id','in',$daziJoinUid)
                    ->field('id,nickname,phone,avatar,sex,age')
                    ->select()->toArray(); // 参加用户
                $userDataById = array_column($userData,null,'id');
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    $daziJoinData[$daziJoinKey]['nickname']  = $userDataById[$daziJoinDatum['uid']]['nickname'];
                    $daziJoinData[$daziJoinKey]['phone']  = $userDataById[$daziJoinDatum['uid']]['phone'];
                    $daziJoinData[$daziJoinKey]['avatar']  = $userDataById[$daziJoinDatum['uid']]['avatar'];
                    $daziJoinData[$daziJoinKey]['sex']  = $userDataById[$daziJoinDatum['uid']]['sex'];
                    $daziJoinData[$daziJoinKey]['age']  = $userDataById[$daziJoinDatum['uid']]['age'];


                }
            }
            foreach ($list as $key => $value){
                $list[$key]['activity_time']= date('Y-m-d H:i',$value['activity_time']);
                $list[$key]['expire_time']= date('Y-m-d H:i',$value['expire_time']);
                $list[$key]['join_data'] = [];
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    if ($value['id'] == $daziJoinDatum['dazi_id']){
                        $list[$key]['join_data'][]= $daziJoinDatum;
                    }
                }
            }
        }
        return success('搭子列表',['list' =>$list,'count'=>$count ]);

    }
    public function daziInfo(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $usreModel = new \app\common\model\User();
        $daziInfo =  $daziModel->where(['id' => $param['id']])->find();
        $userInfo =  $usreModel->where(['id' => $daziInfo['uid']])->find();
        $daziInfo['nickname']  =  $userInfo['nickname'];
        $daziInfo['avatar']  =  $userInfo['avatar'];
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziJoinUser = $daziJoinModel->where(['dazi_id' =>$param['id']])->select()->toArray();
        if (empty($daziJoinUser)){
            $daziInfo['dazi_join_user'] = [];
        }else{
            $joinUid =array_column($daziJoinUser,'uid');
            $userModel = new \app\common\model\User();
            $userList = $userModel->where('id','in',$joinUid)
                ->field('id,nickname,avatar')
                ->select()->toArray();
            $userListById = array_column($userList,null,'id');
            foreach ($daziJoinUser as $key => $value){
                $daziJoinUser[$key]['nickname'] = $userListById[$value['uid']]['nickname'];
                $daziJoinUser[$key]['avatar'] = $userListById[$value['uid']]['avatar'];
            }
            $daziInfo['dazi_join_user'] = $daziJoinUser;
        }
        return success('搭子详情',$daziInfo);

    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *  加入列表
     */
    public function joinDaziList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where =  [] ;
        if (isset($param['dj_status']) &&  !empty($param['dj_status'])) {
            $where[] = ['dj.status','=',$param['dj_status']];
        }
        if (isset($param['status']) && !empty( $param['status'])) {
            $where[] = ['d.status','=',$param['status']];
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['d.title','like','%'.$param['title'].'%'];
        }
        if (isset($param['release_user']) && !empty($param['release_user'])){
            $userModel = new \app\common\model\User();
            $releaseWhere[] = ['nickname|phone','like','%'.$param['release_user'].'%'];
            $releaseList = $userModel ->where($releaseWhere)->select()->toArray();
            if ($releaseList){
                $releaseUserId = array_column($releaseList,'id');
                $where[] = ['d.uid','in',$releaseUserId];
            }else{
                return success('搭子订单列表',['list' =>[],'count'=>0 ]);
            }
        }
        if (isset($param['join_user']) && !empty($param['join_user'])){
            $where[] = ['u.nickname|u.phone','like','%'.$param['join_user'].'%'];

        }
        $daziJoinModel = new \app\common\model\DaziJoin();
        $list = $daziJoinModel
            ->alias('dj')
            ->leftJoin('dazi d', 'd.id = dj.dazi_id')
            ->leftJoin('user u', 'dj.uid = u.id')
            ->where($where)
            ->order('dj.create_time','desc')
            ->field('d.*,u.nickname,u.avatar,u.phone ,dj.status as dj_status ,dj.create_time as dj_create_time')
            ->limit($start,$limit)->select()->toArray();
        if ($list){
            $uidArray = array_column($list,'uid');
            $userModel = new \app\common\model\User();
            $userList = $userModel->where('id','in',$uidArray)->select()->toArray();
            $userListById = array_column($userList,null,'id');
            foreach ($list as  $key => $value){
                $list[$key]['release_user_nickname']  = isset($userListById[$value['uid']]) ? $userListById[$value['uid']]['nickname']:'';
                $list[$key]['release_user_avatar']  =  isset($userListById[$value['uid']]) ? $userListById[$value['uid']]['avatar']:'';
                $list[$key]['release_user_phone']  = isset($userListById[$value['uid']]) ?$userListById[$value['uid']]['phone']:'';
            }
        }

        $count = $daziJoinModel
            ->alias('dj')
            ->leftJoin('dazi d', 'd.id = dj.dazi_id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->where($where)
            ->field('d.*,u.nickname,u.avatar')
            ->count();
        return success('搭子订单列表',['list' =>$list,'count'=>$count ]);
    }
    public function updateDaziStatus(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $daziJoinModel = new \app\common\model\DaziJoin();
        if ($param['status'] == 3 || $param['status'] == 7 ||$param['status'] == 6  ){
            $daziJoinInfo =  $daziJoinModel->where(['dazi_id' => $param['id'],'status' => 1 ])->select()->toArray();
            if ($daziJoinInfo){
                return  error('存在参与的用户，不能');
            }
        }
        $data['status']  =  $param['status'];
        if (isset($param['remark']) && !empty($param['remark'])){
            $data['remark'] = $param['remark'];
        }
        $daziInfo = $daziModel->where(['id' => $param['id']])->find();
        $daziModel->where(['id' => $param['id']])->update($data);
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] =  [
            'thing1' => ['value' => '搭子'],
            'thing2' => ['value' => $daziInfo['title']],
           // 'phrase3' => ['value' =>'通过'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];

        $userModel =  new \app\common\model\User();
        $userInfo  =  $userModel->where(['id' =>$daziInfo['uid'] ])->find();
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'搭子'],
            'thing28' => ['value' => $userInfo['nickname'] ],
            'thing9' => ['value' =>$daziInfo['title']],
        ];
        if ($param['status'] == 2){
            $xcxMessage[0]['data']['phrase3'] = '上架';
            $gzhMessage[0]['data']['thing2'] = '上架';
        }elseif ($param['status'] == 3){
            $xcxMessage[0]['data']['phrase3'] = '下架';
            $gzhMessage[0]['data']['thing2'] = '下架';
        }elseif ($param['status'] = 7){
            $xcxMessage[0]['data']['phrase3'] = '驳回';
            $gzhMessage[0]['data']['thing2'] = '驳回';
        }
        $xcxMessage[0]['uid'] = $daziInfo['uid'];
        $xcxMessage[0]['title'] ='release';
        $gzhMessage[0]['uid'] =$daziInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $messageModel->sendMessage(3,$xcxMessage);
        $messageModel->sendMessage(1,$gzhMessage);
        return  success('操作成功');
    }

    /**
        踢出用户
     */
    public  function  kickUser(Request $request){
        $param = $request->param();
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziModel = new \app\common\model\Dazi();
        $daziJoinInfo  = $daziJoinModel->where(['id' => $param['id']])->find();
        if ($daziJoinInfo['status'] != 1 ){
            return error('此用户已踢出');
        }
        $daziJoinModel->where(['id' => $param['id']])->update(['status' => 2,'update_time' => time()]);
        if ($daziJoinInfo['price']){
            $userModel = new \app\common\model\User();
            $userModel->where(['id' =>$daziJoinInfo['uid'] ])->inc('balance',$daziJoinInfo['price'])->update();
            $userInfo = $userModel->where(['id' =>$daziJoinInfo['uid'] ])->find();
            if ($userInfo['sex'] == 1){
                $participants_number = 'man_participants_number';
            }else{
                $participants_number = 'woman_participants_number';
            }
            $daziModel->where(['id' =>$daziJoinInfo['dazi_id'] ])->dec('participants_number')->dec($participants_number)->update();

            $amountModel = new AmountLog();
            $amountData  = [
                'uid' => $daziJoinInfo['uid'],
                'amount' => $daziJoinInfo['price'],
                'amount_type' => 1,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id' => $param['id'],
                'operation_source' => 3
            ];
            $amountModel->insert($amountData);
        }
        $daziInfo =  $daziModel->where(['id' => $daziJoinInfo['dazi_id']])->find();
        $xcxMessage[0]['data'] = [
            'thing1' => ['value' => '搭子'],
            'thing2' => ['value' => $daziInfo['title']],
            'phrase3' => ['value' =>'后台移除'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] =$daziJoinInfo['uid'];
        $xcxMessage[0]['title'] ='release';

        $xcxMessage[1]['data'] = [
            'thing1' => ['value' => '搭子'],
            'thing2' => ['value' => $daziInfo['title']],
            'phrase3' => ['value' =>'后台移除'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[1]['uid'] =$daziInfo['uid'];
        $xcxMessage[1]['title'] ='release';
        $userModel =  new \app\common\model\User();
        $userInfo  =  $userModel->where(['id' =>$daziInfo['uid'] ])->find();
        $userJoinInfo  =  $userModel->where(['id' =>$daziJoinInfo['uid'] ])->find();
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'搭子'],
            'thing28' => ['value' => $userInfo['nickname'] ],
            'thing9' => ['value' =>$daziInfo['title']],
            'thing2' => ['value' => '后台移除'],
        ];
        $gzhMessage[0]['uid'] =$daziInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $gzhMessage[1]['data'] = [
            'thing10' => ['value' =>'搭子'],
            'thing28' => ['value' => $userJoinInfo['nickname'] ],
            'thing9' => ['value' =>$daziInfo['title']],
            'thing2' => ['value' => '后台移除'],
        ];
        $gzhMessage[1]['uid'] =$userJoinInfo['uid'];
        $gzhMessage[1]['title'] ='release';
        $messageModel = new MessageTemplate();
        $messageModel->sendMessage(3,$xcxMessage);
        $messageModel->sendMessage(1,$gzhMessage);
        return  success('操作成功');
    }
    public function editDazi(Request $request){
        $param = $request->param();
        $data= [
            'title' => $param['title'],
            'people_number' => $param['people_number'],
            'address' => $param['address'],
            'sex' => $param['sex'],
            'pid_tab' => $param['pid_tab'],
            'son_tab' => $param['son_tab'],
            'activity_time' => strtotime($param['activity_time']),
            'expire_time' => strtotime($param['expire_time']),
            'create_time' =>  time(),
            'cover_img' => $param['cover_img'],
            'wechat' => $param['wechat'],
            'phone' => $param['phone'],
            'label' => $param['label'],
            'img' => $param['img'],
            'describe' => $param['describe'],
            'uid' => $request->userInfo['id'],
            'price' => $param['price'],
            'longitude' => $param['longitude'],
            'dimension' => $param['dimension'],
        ];

        if (strtotime($param['activity_time'])< time()){
            return error('活动不能小于当前时间');
        }
        if (strtotime($param['expire_time'])< time()){
            return error('报名时间不能小于当前时间');
        }

        if (strtotime($param['expire_time'])> strtotime($param['activity_time'])){
            return error('报名时间不能大于活动时间');
        }
        $longitude = number_format(doubleval($data['longitude']), 6);
        $latitude = number_format(doubleval($data['dimension']), 6);
        $gps = $latitude . ',' . $longitude;

        $params = array(
            'location' => $gps,
            'key'=> \app\common\model\Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult  = json_decode(curlGet($url));
        if ($mapResult->status == 0 ){
            /* return error('百度地图数据获取有误')*/
            $data['province_name'] = isset ($mapResult->result->address_component->province)?$mapResult->result->address_component->province :0 ;
            $data['city_name'] = $mapResult->result->address_component->city;
            $data['area_name'] = $mapResult->result->address_component->district;
            //$user['address'] = $mapResult->result->address;
        };

        $daziModel = new \app\common\model\Dazi();
        $daziInfo = $daziModel->where(['id' => $param['id']])->find();
        if ($daziInfo['participants_number']){
            return error('已有用户参与');
        }
        $daziModel->where(['id' => $param['id']])->update($data);
        return success('修改成功');
    }

    /**
     * 踢出全部用户

     */
    public function kickAllUser(Request $request){
        $param = $request->param();
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziModel = new \app\common\model\Dazi();
        $daziJoinList = $daziJoinModel->where(['dazi_id' => $param['id'],'status' => 1])->select()->toArray();
        $userModel = new \app\common\model\User();
        foreach ($daziJoinList as $key => $value){
            if ($value['price']){
                $userModel->where(['id' =>$value['uid'] ])->inc('balance',$value['price'])->update();
                $userInfo = $userModel->where(['id' =>$value['uid'] ])->find();
                if ($userInfo['sex'] == 1){
                    $participants_number = 'man_participants_number';
                }else{
                    $participants_number = 'woman_participants_number';
                }
                $daziModel->where(['id' =>$value['dazi_id'] ])->dec('participants_number')->dec($participants_number)->update();

                $amountModel = new AmountLog();
                $amountData  = [
                    'uid' => $value['uid'],
                    'amount' => $value['price'],
                    'amount_type' => 1,
                    'amount_direction' => 1,
                    'create_time' => time(),
                    'correlation_id' => $value['id'],
                    'operation_source' => 3
                ];
                $amountModel->insert($amountData);
            }
            $daziJoinModel->where(['id' => $value['id']])->update(['status' => 2,'update_time' => time()]);
        }
        return  success('操作成功');
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     *   搭子 置顶记录
     */
    public function daziTopList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where =[] ;
        if ( isset($param['status']) && !empty($param['status']) ){
            $where[] = ['d.status','=',$param['status']];
        }

        if (isset($param['nickname']) && !empty($param['nickname'])){
            $where[] = ['u.nickname','like','%'.$param['nickname'].'%'];
        }
        if (isset($param['phone']) && !empty($param['phone'])){
            $where[] = ['u.phone','=',$param['phone']];
        }
        if (isset($param['uid']) && !empty($param['uid'])){
            $where[] = ['d.uid','=',$param['uid']];
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['d.title','like','%'.$param['title'].'%'];
        }
        $daziTopLogModel = new \app\common\model\DaziTopLog();
        $list = $daziTopLogModel
            ->alias('dt')
            ->leftJoin('dazi d', 'dt.dazi_id = d.id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->order('d.create_time','desc')
            ->where($where)
            ->field('d.*,u.nickname,u.avatar,dt.*')
            ->limit($start,$limit)->select()->toArray();
        $count = $daziTopLogModel
            ->alias('dt')
            ->leftJoin('dazi d', 'dt.dazi_id = d.id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->where($where)
           ->count();
        foreach ($list as $key => $value){
            if ($value['top_expire_time'] > 0){
                $list[$key]['effective_time'] = date('Y-m-d H:i', $value['effective_time']);
            }

        }
        return success('搭子置顶记录',['list' =>$list,'count'=>$count ]);

    }

}